package com.glory.dgcpcpda.activity.mfg;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.AddCarrierDataAdapter;
import com.glory.dgcpcpda.adapter.LotBatchListAdapter;
import com.glory.dgcpcpda.adapter.LotQcBatchListAdapter;
import com.glory.dgcpcpda.adapter.MaterielListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.MaterielListEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class QCWorkActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.lotQty)
    TextView lotQty;
    @BindView(R.id.tvStepDesc)
    TextView tvStepDesc;
    @BindView(R.id.tvRecipeID)
    TextView tvRecipeID;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.tvLotHoldState)
    TextView tvLotHoldState;
    @BindView(R.id.tvCount)
    TextView tvCount;


    public LotQcBatchListAdapter mAdapter;
    private int mCount = 0;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_in_out_qc;
    }

    @Override
    protected void initView() {
        tvTitle.setText("QC过站");
        setMainLayout(llMain);

        initRecyclerView(rvLotList,this);
        tvCount.setText("" + mCount);
        mAdapter = new LotQcBatchListAdapter(null);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        rvLotList.setAdapter(mAdapter);

        initEdit(etLot, s -> {
            //获取lot信息
            lotInfo(s,false);

        });


    }

    /**
     * 是否显示载具
     * @param data
     */
    private void showCarrierLayout(LotInfoEntity data) {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<AdrefListEntity.Adref> adreflist = response.body().getResponse().getBody().getADREFLIST();
                    for (AdrefListEntity.Adref entity : adreflist) {
                        if (entity.getTEXT().equals(data.getLOT().getSTEPNAME())) {
                           // llCarrierLayout.setVisibility(View.VISIBLE);
                            return;
                        }
                    }

                   // llCarrierLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","CPC_CARRIERS_CHECK_STEP");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }



    @Override
    protected void initData() {

    }

    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
        if (actionControl("Submit23"))
            return;

        if(!tvStepDesc.getText().toString().equals("键合QC")&&!tvStepDesc.getText().toString().equals("三目视（QC Gate）")){
            showToast("该功能只用于QC过站，不允许其他工序使用!",false);
            etLot.setText("");
            etLot.setFocusable(true);
            return;
        }


        if (getText(etUserName).equals("")){
            showToast("请输入工号",false);
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(),  getSupportFragmentManager(), QCWorkActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){

                    submitOut(getText(etLot),lotQty.getText().toString());

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                FreeApi_LogUtils.saveErrorMessages(response.getException(), "LOTTRACKIN");
                FreeApi_ToastUtils.showFreeToast("连接服务器失败",getApplicationContext(),false,0);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","NoEqpTrackIn");
        map.addProperty("EQUIPMENTID","");
        map.addProperty("ISCHECKSTEPAUTHORITY",true);
       // map.add("DURABLELIST",new JsonParser().parse(new Gson().toJson(carrierAdapter.getData())).getAsJsonArray());
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(getText(etLot)));
        map.add("LOTLIST",new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
//                map.addProperty("LOTACTIONLIST",etLot.getText().toString());//传批次动作列表
        NetUtils.mRequestPostNet("CPC.LOTTRACKIN",getText(etUserName),"LOTTRACKIN",getApplicationContext(),map,callBack);



    }
    private void submitOut(String lotID,String mainQTY){
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), QCWorkActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    showToast("过站成功",true);
                    lotInfo(response.body().getResponse().getBody().getLOTLIST().get(0).getLOTID(),true);




                    clean();
                    etLot.setFocusable(true);

                }

            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"TRACKOUT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","NoEqpTrackOut");
        map.addProperty("EQUIPMENTID","");
        map.addProperty("ISCHECKSTEPAUTHORITY",true);
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID,mainQTY));
        map.add("LOTLIST",new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
        NetUtils.mRequestPostNet("CPC.LOTTRACKOUT",getText(etUserName),"LOTTRACKOUT",QCWorkActivity.this,map,callBack);
//        NetUtils.requestMESPostNet("CPC.LOTTRACKOUT",WorkBatchEndActivity.this,map,callBack);
    }

    private void lotInfo(String lotId,boolean flag){
        LotUtils.searchLotInfo(QCWorkActivity.this, lotId, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(LotInfoEntity response) {
                if(flag){


                    mAdapter.addData(response);

                    tvCount.setText("" + mAdapter.getData().size());
                }else {
                    showCarrierLayout(response);
                    tvTitle.setText("开始作业" + "(" + response.getLOT().getSTEPDESC() + ")");
                    lotQty.setText(response.getLOT().getMAINQTY());
                    String state = response.getLOT().getSTATE();
                    if (state.equals("正在作业")) {
                        state = state + " - " + response.getLOT().getEQUIPMENTID();
                    }
                    if(StringUtils.isNotEmpty(response.getHOLDREASON())){

                        showConfirmDialog("该批次被暂扣，原因如下\n"+response.getHOLDREASON());
                       // FreeApi_ToastUtils.showFreeToast(response.getHOLDREASON(),getApplicationContext(),true,0);
                    }
                    tvLotHoldState.setText(response.getLOT().getHOLDSTATE());
                    tvLotState.setText(state);
                    tvStepDesc.setText(response.getLOT().getSTEPDESC());
                }
            }
            @Override
            public void onFail(Throwable t) {
                loadError(t, "LOTQUERY");
                showConfirmDialog(QCWorkActivity.this,"接口不通");
            }
        });
    }
    private void clean(){
        etLot.setText("");
        lotQty.setText("");
        tvStepDesc.setText("");
        tvLotState.setText("");
        tvLotHoldState.setText("");
    }
}
